<template>
  <div class="container">

  </div>
</template>

<script>
  //引入d3  安装 npm install --save d3@5.15.0
  import * as d3 from 'd3'

  export default {
    name: 'HelloWorld',
    data() {
      return {
        //设置宽高
        width:800,
        height:500,
        //在画布上显示的节点和关系
        links:[{"source": " ", "target": " ", "value": 1}],
        nodes:[],
        //关系和节点的名称
        linkName:[],
        nodeName:"",
        //画布和模拟器
        simulation:null,
        svgArea:null,
        //颜色列表
        colorList:['red','yellow','#123501','#223344','yellow','black','#002266',
          '#ffee11','#aebc23','red','blue','#123501','#223344',
          'yellow','black','#002266','#ffee11','#aebc23'],
        //节点和关系的数据
        testGraph: {
          "links":[],
          "nodes":[],
        }
      }
    },
    created() {
      const _this=this;
      //向后端发送请求
      // this.axios.get("http://localhost:8329/api/person/Tom Cruise")
      this.axios.get("http://localhost:8329/api/person/all")
        .then(function (response) {
          _this.testGraph["nodes"]=response.data
          //异步的 不然还是空数据
          //初始化节点和关系
          _this.init(_this.testGraph)
        })
        .catch(function (response) {
          console.log(response)
        })

    },
    methods: {
      init(data) {
        const _this=this;
        //去掉无影响
        // const links = data.links.map(d => Object.create(d));
        // const nodes = data.nodes.map(d => Object.create(d));
        const links = data.links;
        const nodes = data.nodes;
        //设置力的导向等...
        _this.simulation = d3.forceSimulation(nodes)
          //结点碰撞
          // .force("collide",d3.forceCollide().radius(()=>30))
          //设置表示关系的线的长度
          .force("link", d3.forceLink(links).id(d => d.id).distance(200))
          .force("charge", d3.forceManyBody().strength(-30))
          .force("center", d3.forceCenter(_this.width / 2, _this.height / 2));

        //用来放node和link的容器
        //选中container类 SVG 意为可缩放矢量图形。
        _this.svgArea=d3.select(".container")
          //添加一个svg元素
          .append("svg")
          //添加一个视图盒子  设置宽高
          .attr("viewBox", [0, 0, _this.width, _this.height])
          //设置滚轮缩小放大
          .call(d3.zoom().on("zoom",function () {
            g.attr("transform",d3.event.transform)
          }))
        //svg中添加一个g元素 并设置类名
        const g = _this.svgArea.append("g")
          .attr("class","content")

        //设置关系
        _this.links = g.append("g")
          //元素轮廓颜色
          .attr("stroke", "#999")
          //边框颜色的透明度
          .attr("stroke-opacity", 0.6)
          //'join'  data中的每个数据到selection中的每个元素上
          .selectAll("path")
          .data(links)
          .join("path")
          .attr("marker-end", "url(#positiveMarker)")
          //边框宽度
          .attr("stroke-width", d => Math.sqrt(d.value))
          //添加类属性
          .attr("class","link")
          //设置id 为了后面给关系添加文字用  textPath的href是这个id
          .attr("id",d=>d.source+"_"+d.relationship+"_"+d.target)

        _this.nodes = g.append("g")
          //'join'  data中的每个数据到selection中的每个元素上
          .selectAll("circle")
          .data(nodes,d=>d.id)
          .join("circle")
          //设置半径
          .attr("r", 30)
          //给圆填充颜色
          .attr("fill", this.color)
          //添加拖动事件
          .call(this.drag(_this.simulation))
          //添加类名
          .classed("node",true)
          //添加点击事件 好像没用
          .on("click",this.nodeClick)

        //给node加一个名字 鼠标放上去显示
        _this.nodes.append("title")
          .text(d => d.id);
        //把名字加到圆的下面
        _this.nodeName=g.append("g")
          //'join'  data中的每个数据到selection中的每个元素上
          .selectAll("text")
          .data(nodes)
          .join("text")
          //类名
          .attr("class","nodeName")
          //设置文本内容
          .text(d => d.id)
          //文字填充白色
          .attr("fill","white")
          //x y 相对于圆心的偏移量
          .attr("dy",50)
          .attr("dx",function () {
            return this.getBoundingClientRect().width/2*(-1)
          })

        _this.linkName=g.append("g")
          .selectAll("path")
          .data(links)
          .join("path")
          //设置居中
          .attr('startOffset','50%')
          //设置各种样式
          .style('text-anchor','middle')
          .style('fill','black')
          .style('font-size','10px')
          .style('font-weight','bold')
          //添加文字路径 上面link的id
          .append("textPath")
          .attr(
            'xlink:href',d =>"#"+d.source+"_"+d.relationship+"_"+d.target
          )
          //文字内容
          .text(function (d) {
            return d.relationship;
          });
          //设置模拟....
        _this.simulation.on("tick", () => {
          _this.links
            .attr("d", function(d){
              //设置箭头的方向 改变source和target 为了linkName不倒过来
              if(d.source.x<d.target.x){
                return "M "+d.source.x+" "+ d.source.y +" L "+d.target.x+" "+d.target.y
              }
              else{
                return "M "+d.target.x+" "+ d.target.y +" L "+d.source.x+" "+d.source.y
              }
            })
            //添加一个箭头 计算是正着的关系还是倒着的关系
            .attr("marker-end",function (d) {
              if(d.source.x<d.target.x){
                return "url(#positiveMarker)"
              }
              else{
                return null
              }
            })
            .attr("marker-start",function (d) {
              if(d.source.x<d.target.x){
                return null
              }
              else{
                return "url(#negativeMarker)"
              }
            })
            // .attr("d",d => "M "+d.source.x+" "+d.source.y+" L "+d.target.x+" "+d.target.y);
            // .attr("x1", d => d.source.x)
            // .attr("y1", d => d.source.y)
            // .attr("x2", d => d.target.x)
            // .attr("y2", d => d.target.y);

          _this.nodes
            .attr("cx", d => d.x)
            .attr("cy", d => d.y);

          _this.nodeName
            .attr("x",d=>d.x)
            .attr("y",d=>d.y)
        });
        //添加箭头
        this.addMarkers();
      },
      color(d){
        //自己写个颜色数组测试
        return this.colorList[d.group]
        // const scale = d3.scaleOrdinal(d3.schemeCategory10);
        // return d => scale(d.group);
      },
      /*
      * 文档自带的拖拽设置
      * */
      drag(simulation) {
        function dragstarted(d) {
          if (!d3.event.active) simulation.alphaTarget(0.3).restart();
          d.fx = d.x;
          d.fy = d.y;
        }

        function dragged(d) {
          d.fx = d3.event.x;
          d.fy = d3.event.y;
        }

        function dragended(d) {
          if (!d3.event.active) simulation.alphaTarget(0.5);
          d.fx = null
          d.fy = null
        }

        return d3.drag()
          .on("start", dragstarted)
          .on("drag", dragged)
          .on("end", dragended);
      },
      /*
      * 结点的点击响应事件
      * */
      nodeClick(d) {
        const _this=this;
        //向后端发送请求 获取和人有关的电影信息
        this.axios.get("http://localhost:8329/api/person/actedby/"+d.id)
          .then(function (response) {
            //防止重复添加节点
            for(var i=0;i<response.data.length;i++){
              let flag=true;
              for(var j=0;j<_this.testGraph.nodes.length;j++){
                if(_this.testGraph.nodes[j].id===response.data[i].id){
                  flag=false;
                  break;
                }
              }
              if(flag){
                //如果不是重复点击 就往nodes和links里添加新的信息
                _this.testGraph.nodes.push(response.data[i])
                _this.testGraph.links.push({
                  "source": d.id,
                  "target": response.data[i].id,
                  "value": 5,
                  "relationship":"ACTED_IN"
                })
              }
            }
            //更新图像
            _this.updateGraph(_this.testGraph)
          })
          .catch(function (response) {
            console.log(response)
          })
      },
      /*
      * 节点点击之后的更新图像
      * 和初始化类似
      * */
      updateGraph(data){
        const _this=this;
        const links = data.links;
        const nodes = data.nodes;

        _this.links=_this.links
          .data(links,(d)=>{return d.source.id+"-"+d.target.id;})
          .enter()
          .append("path")
          .attr("stroke", "#999")
          .attr("stroke-opacity", 0.6)
          .attr("stroke-width", d => Math.sqrt(d.value))
          .attr("marker-end", "url(#positiveMarker)")
          .merge(_this.links)
          .attr("class","link")
          .attr("id",d=>d.source+"_"+d.relationship+"_"+d.target)

        _this.nodes = _this.nodes
          .data(nodes)
          .enter()
          .append("circle")
          .attr("r", 30)
          .attr("class","node")
          .attr("fill", this.color)
          .merge(_this.nodes)
          .on("click",this.nodeClick)
          .call(_this.drag(_this.simulation))

        _this.nodes.append("title")
          .text(d => d.id);
        _this.nodeName=_this.nodeName
          .data(nodes)
          .join("text")
          .attr("class","nodeName")
          .text(d => d.id)
          .attr("fill","white")
          .attr("dy",50)
          .attr("dx",function () {
            return this.getBoundingClientRect().width/2*(-1)
          })

        _this.linkName = _this.linkName
          .data(links)
          .enter()
          .append('text')
          .style('text-anchor','middle')
          .style('fill', 'white')
          .style('font-size', '10px')
          .style('font-weight', 'bold')
          .append('textPath')
          .attr(
            'xlink:href',d=>"#"+d.source+"_"+d.relationship+"_"+d.target
          )
          .attr('startOffset','50%')
          .merge(_this.linkName)
          .text(function (d) {
            return d.relationship;
          })

        _this.simulation.nodes(nodes)
        _this.simulation.force("link").links(links)
        _this.simulation.alpha(0.2).restart()
      },
      //添加箭头
      addMarkers(){
        //设置箭头的样式 ..略过
        const positiveMarker = this.svgArea.append("marker")
          .attr("id","positiveMarker")
          .attr("orient","auto")
          .attr("stroke-width",2)
          .attr("markerUnits", "strokeWidth")
          .attr("markerUnits", "userSpaceOnUse")
          .attr("viewBox", "0 -5 10 10")
          .attr("refX", 35)
          .attr("refY", 0)
          .attr("markerWidth", 12)
          .attr("markerHeight", 12)
          .append("path")
          .attr("d", "M 0 -5 L 10 0 L 0 5")
          .attr('fill', '#999')
          .attr("stroke-opacity", 0.6);
        const negativeMarker = this.svgArea.append("marker")
          .attr("id","negativeMarker")
          .attr("orient","auto")
          .attr("stroke-width",2)
          .attr("markerUnits", "strokeWidth")
          .attr("markerUnits", "userSpaceOnUse")
          .attr("viewBox", "0 -5 10 10")
          .attr("refX", -25)
          .attr("refY", 0)
          .attr("markerWidth", 12)
          .attr("markerHeight", 12)
          .append("path")
          .attr("d", "M 10 -5 L 0 0 L 10 5")
          .attr('fill', '#999')
          .attr("stroke-opacity", 0.6);
      },
    }
  }
</script>


<style >
  body{
    margin: 0px;
  }
  .container{
    width: 800px;
    height: 500px;
    border: 1px solid #2c3e50;
    border-radius:8px;
    margin-top: 40px;
    margin-left: auto;
    margin-right: auto;
    background: #154360 repeating-linear-gradient(30deg,
    hsla(0, 0%, 100%, .1), hsla(0, 0%, 100%, .1) 15px,
    transparent 0, transparent 30px);
  }
  .node{
    stroke:#fff;
    stroke-width:1;
    cursor: pointer;
  }
  .node:hover{
    stroke-width:5;
  }
  .nodeName{
    fill:white;
  }
</style>
